package com.sskj.gcc.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.gcc.R;
import com.sskj.gcc.bean.ServiceLinkBean;
import com.sskj.gcc.component.DaggerUserDataComponent;
import com.sskj.gcc.presenter.SlideMineFragmentPresenter;
import com.sskj.gcc.ui.activity.BillingDetailsActivity;
import com.sskj.gcc.ui.activity.ChargeMoneyActivity;
import com.sskj.gcc.ui.activity.KeFuWebViewActivity;
import com.sskj.gcc.ui.activity.WithdrawActivity;
import com.sskj.gcc.util.AppTipUtil;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.NoLoginDialog;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.Constants;
import com.sskj.gocoin.m.HttpConfig;
import com.sskj.gocoin.m.bean.UserInfo;
import com.sskj.gocoin.mine.FeedBackActivity;
import com.sskj.gocoin.mine.MyShareActivity;
import com.sskj.gocoin.utils.CopyUtil;
import com.sskj.gocoin.utils.PhoneHideUtil;
import com.sskj.gocoin.utils.SPUtils;
import com.sskj.gocoin.v.activity.CashAddressListActivity;
import com.sskj.gocoin.v.activity.GoogleSettingActivity;
import com.sskj.gocoin.v.activity.MainActivity;
import com.sskj.gocoin.v.activity.PersonalActivity;
import com.sskj.gocoin.v.activity.SecurityCenterActivity;
import com.sskj.gocoin.v.activity.ShareActivity;
import com.sskj.gocoin.v.base.BaseFragment;
import com.sskj.lib.RConfig;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.TipUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import me.jessyan.autosize.utils.ScreenUtils;

import static android.app.Activity.RESULT_OK;

@Route(path = RConfig.APP_MINE)
public class MineFragment extends BaseFragment<MainActivity, SlideMineFragmentPresenter> {

    @BindView(R.id.rightView)
    View rightView;
    @BindView(R.id.llRoot)
    LinearLayout llRoot;


    @BindView(R.id.iv_photo)
    ImageView ivPhoto;
    @BindView(R.id.tvAccount)
    TextView tvAccount;
    @BindView(R.id.tvUid)
    TextView tvUid;
    @BindView(R.id.tvPerson)
    TextView tvPerson;
    @BindView(R.id.tvSecurityCenter)
    TextView tvSecurityCenter;
    @BindView(R.id.tvWithdrawAddress)
    TextView tvWithdrawAddress;
    @BindView(R.id.tvMyPopularize)
    TextView tvMyPopularize;
    @BindView(R.id.tvContactCustomerService)
    TextView tvContactCustomerService;
    @BindView(R.id.tvContactUs)
    TextView tvContactUs;
    @BindView(R.id.tvFeedBack)
    TextView tvFeedBack;
    @BindView(R.id.tvSetting)
    ImageView tvSetting;
    @BindView(R.id.llSign)
    LinearLayout llSign;
    @BindView(R.id.tvSign)
    TextView tvSign;
    @BindView(R.id.tvAssetDetail)
    TextView tvAssetDetail;
    @BindView(R.id.llInfo)
    LinearLayout llInfo;
    @BindView(R.id.invitation_friend)
    RelativeLayout invitationFriend;
    @BindView(R.id.tv_money_01)
    TextView tvMoney01;
    @BindView(R.id.tv_money_02)
    TextView tvMoney02;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;


    private UserInfo mUserInfo;
    @Inject
    UserViewModel userViewModel;
    private ServiceLinkBean serviceLinkBean;
    private AlertDialog dialog;

    @BindView(R.id.tvChargeMoney)
    TextView tvChargeMoney;
    @BindView(R.id.tvWithdrawMoney)
    TextView tvWithdrawMoney;

    private final int SELECT_PHOTO = 1001;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine;
    }


    @Override
    public SlideMineFragmentPresenter getPresenter() {
        return new SlideMineFragmentPresenter();
    }


    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.requestUserInfo();
            } else {
                userData = null;
                updateStatus(null);
            }
        });

        mPresenter.getEmail();

        smartRefreshLayout.setRefreshHeader(new MaterialHeader(getActivity()));

        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            mPresenter.requestUserInfo();
        });

        ClickUtil.click(rightView, new ClickUtil.Click() {
            @Override
            public void click() {
                llRoot.setBackgroundColor(Color.TRANSPARENT);
            }
        });

        ClickUtil.click(llInfo, () -> {
            if (userData == null) {
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                return;
            }
            startActivity(new Intent(getActivity(), PersonalActivity.class));
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });

        ClickUtil.click(invitationFriend, () -> {
            if (userData == null) {
                ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                return;
            }
            ShareActivity.start(getActivity());
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });

        /**
         * 修改头像
         */
        ClickUtil.click(ivPhoto, () -> selectImage(SELECT_PHOTO));

        //充币
        ClickUtil.click(tvChargeMoney, new ClickUtil.Click() {
            @Override
            public void click() {
                if (userData == null) {
                    ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                    getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
                    return;
                }
                //未绑定啥也不能干
                //    if (userData.getConfig().getGoogle_bind() == 0) {
                if (false) {
                    TipUtil.googleBindTip(getActivity(), getString(R.string.lib_google_bind), () -> {
                        ARouter.getInstance().build(RConfig.MINE_SECURITY).navigation();
                    });
                } else {
                    ChargeMoneyActivity.start(getActivity());
                }
            }
        });
        //提币
        ClickUtil.click(tvWithdrawMoney, new ClickUtil.Click() {
            @Override
            public void click() {
                if (userData == null) {
                    ARouter.getInstance().build(RConfig.APP_LOGIN).navigation();
                    getActivity().overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
                    return;
                }
                //未绑定啥也不能干
                //  if (userData.getConfig().getGoogle_bind() == 0) {
                if (false) {
                    TipUtil.googleBindTip(getActivity(), getString(R.string.lib_google_bind), () -> {
                        ARouter.getInstance().build(RConfig.MINE_SECURITY).navigation();
                    });
                } else {
                    check();
                }
            }
        });

        //个人资料
        ClickUtil.click(tvPerson, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), PersonalActivity.class));
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });
        //安全中心
        ClickUtil.click(tvSecurityCenter, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), SecurityCenterActivity.class));
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });
        //提币地址
        ClickUtil.click(tvWithdrawAddress, () -> {
            if (!isLogin()) return;
            if (!googleBind()) {
                return;
            }
            startActivity(new Intent(getActivity(), CashAddressListActivity.class));
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });
        //我的推广
        ClickUtil.click(tvMyPopularize, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), MyShareActivity.class));
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });
        //账单明细
        ClickUtil.click(tvAssetDetail, () -> {
            if (!isLogin()) return;
            startActivity(new Intent(getActivity(), BillingDetailsActivity.class));
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });


        //联系客服
        ClickUtil.click(tvContactCustomerService, () -> {
            if (serviceLinkBean != null) {
                if (!TextUtils.isEmpty(serviceLinkBean.getService_link())) {
                    KeFuWebViewActivity.start(getActivity(), serviceLinkBean.getService_link());
                }
            }
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });


        //联系我们
        ClickUtil.click(tvContactUs, () -> {
            View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_connect, null);
            AlertDialog dialog = new AlertDialog.Builder(getActivity(), R.style.custom_dialog)
                    .setView(dialogView)
                    .show();
            Window window = dialog.getWindow();
            int[] size = ScreenUtils.getScreenSize(getActivity());
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = (int) (size[0] * 0.9f);
            window.setAttributes(layoutParams);
            TextView textView = dialogView.findViewById(com.sskj.gocoin.R.id.content);
            TextView close = dialogView.findViewById(com.sskj.gocoin.R.id.close);
            TextView tvCopy = dialogView.findViewById(com.sskj.gocoin.R.id.tvCopy);
            setText(textView, email);
            Button button = dialogView.findViewById(com.sskj.gocoin.R.id.submit);
            button.setOnClickListener(v -> dialog.dismiss());
            close.setOnClickListener(v -> dialog.dismiss());
            tvCopy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!TextUtils.isEmpty(email)) {
                        CopyUtil.copy(email);
                        dialog.dismiss();
                    }
                }
            });
        });

        //意见反馈
        ClickUtil.click(tvFeedBack, () -> {
            FeedBackActivity.start(getActivity());
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });
        //设置
        ClickUtil.click(tvSetting, () -> {
            if (isActivityAlive(getActivity()))
                startActivity(new Intent(getActivity(), GoogleSettingActivity.class));
            llRoot.setBackgroundColor(Color.TRANSPARENT);
        });
        //签到
        ClickUtil.click(llSign, () -> {
            if (!isLogin()) return;
            if (App.INSTANCE.getString(R.string.signed).equals(tvSign.getText().toString().trim())) {
                return;
            }
            mPresenter.signIn();
        });
    }

    private boolean isLogin() {
        if (userData == null) {
            NoLoginDialog noLoginDialog = new NoLoginDialog(getActivity());
            noLoginDialog.show();
            return false;
        }
        return true;
    }

    public void updateStatus(UserInfo data) {
        try {
            if (AppTipUtil.isActivityAlive(getActivity())) {
                if (smartRefreshLayout != null)
                    smartRefreshLayout.finishRefresh();
                mUserInfo = data;
                if (data != null) {
                    SPUtils.putBean(MyAppLication.getApplication(), Constants.SP_USER_INFO, data);
                    SPUtils.put(MyAppLication.getApplication(), Constants.SP_REALNAME, data.getName());
                    SPUtils.put(MyAppLication.getApplication(), Constants.SP_REALNAME_STATUS, data.getAuthentication());
                    tvUid.setVisibility(View.VISIBLE);
                    if (data.getQd() == 1) {
                        tvSign.setText(App.INSTANCE.getString(com.sskj.gocoin.R.string.signed));
                    } else {
                        tvSign.setText(App.INSTANCE.getString(com.sskj.gocoin.R.string.sign));
                    }
                    String s = SPUtil.get(Constants.SP_MOBILE, "");
                    if (TextUtils.isEmpty(data.getName())) {
                        if (!s.contains("@")) {
                            tvAccount.setText(data == null ? App.INSTANCE.getString(com.sskj.gocoin.R.string.fabimineJavaMineFragment4) : PhoneHideUtil.getHide(s));
                        } else {
                            tvAccount.setText(data == null ? App.INSTANCE.getString(com.sskj.gocoin.R.string.fabimineJavaMineFragment4) : PhoneHideUtil.getEmailHide(s));
                        }
                    } else {
                        tvAccount.setText(data.getName());
                    }

                    if (!TextUtils.isEmpty(data.getAvatar())) {
                        Glide.with(this).load(HttpConfig.BASE_URL + data.getAvatar()).into(ivPhoto);
                    }
                    tvUid.setText(data == null ? "--" : "UID:" + data.getAccount());

                    switch (data.getConfig().getJd_level()) {
                        case 0:
                            tvUid.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null);
                            break;
                        case 1:
                            //  tvUid.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.f1), null);
                            tvUid.setText(tvUid.getText() + getResources().getString(R.string.level_f1));
                            break;
                        case 2:
                            //   tvUid.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.f2), null);
                            tvUid.setText(tvUid.getText() + getResources().getString(R.string.level_f2));
                            break;
                        case 3:
                            //  tvUid.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.f3), null);
                            tvUid.setText(tvUid.getText() + getResources().getString(R.string.level_f3));
                            break;
                        case 4:
                            //   tvUid.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.f4), null);
                            tvUid.setText(tvUid.getText() + getResources().getString(R.string.level_f4));
                            break;

                    }

                    tvMoney01.setText(String.valueOf(data.getWallasset().getTtl_usdt()));
                    tvMoney02.setText("≈" + String.valueOf(data.getWallasset().getTtl_rmb()) + " CNY");


//            if (mUserInfo.isIs_shop()) {
//                menuData.set(5, new Menu(App.INSTANCE.getString(R.string.fabimineJavaMineFragment12), R.mipmap.h_mine_apply_seller, SellerApplyActivity.class));
//                menuAdapter.notifyDataSetChanged();
//            } else {
//                menuData.set(5, new Menu(App.INSTANCE.getString(R.string.strMineFragment210), R.mipmap.h_mine_apply_seller, SellerApplyActivity.class));
//                menuAdapter.notifyDataSetChanged();
//            }
                } else {
                    tvAccount.setText(App.INSTANCE.getString(R.string.my_login_rigister));
                    tvUid.setText("--");
                    tvUid.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void signInSuccess() {
        tvSign.setText(App.INSTANCE.getString(com.sskj.gocoin.R.string.signed));
    }

    public void onRelieveBusinessSuccess() {
        if (dialog != null) {
            dialog.dismiss();
        }
        mUserInfo.is_shop = false;
        userData.setIs_shop(0);
        userViewModel.update(userData);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (userViewModel != null) {
            userViewModel.update();
        }
    }

    /**
     * 谷歌绑定
     */
    private boolean googleBind() {
        // if (userData.getConfig().getGoogle_bind() == 0) {
        if (false) {
            TipUtil.googleBindTip(getActivity(), getString(com.sskj.gocoin.R.string.lib_google_bind), () -> {
                ARouter.getInstance().build(RConfig.MINE_SECURITY).navigation();
            });
            return false;
        } else {
            return true;
        }
    }


    @SuppressLint("CheckResult")
    private void selectImage(int requestCode) {
        new RxPermissions(getActivity())
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) {
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())
                                .previewImage(true)
                                .isCamera(true)
                                .imageFormat(PictureMimeType.JPEG)
                                .maxSelectNum(1)
                                .compress(true)
                                .forResult(requestCode);
                    }
                });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            if (selectList != null && selectList.size() > 0) {
                LocalMedia media = selectList.get(0);
                String url;
                if (media.isCompressed()) {
                    url = media.getCompressPath();
                } else {
                    url = media.getPath();
                }
                switch (requestCode) {
                    case SELECT_PHOTO:
                        Glide.with(this).load(url).into(ivPhoto);
                        break;
                }
                mPresenter.uploadPic(new File(url));
            }
        }
    }

    String email = "";

    public void setEmail(String emailStr) {
        email = emailStr;
    }

    private void check() {
        if (mUserInfo == null) {
            return;
        }
        if (checkIdent(getActivity())) {
            if (checkPwdStatus()) {
                if (checkIdentHign(getActivity())) {
                    WithdrawActivity.start(getActivity());
                }
            }
        }
    }
}
